<template>
  <Header />
  <div class="login-page">
    <!-- 左侧欢迎信息 -->
    <div class="welcome-section">
      <div class="welcome-text">
        <div>
          <h1>欢迎登录</h1>
          <h2>广州殡葬服务中心项目管理服务平台</h2>
        </div>

        <el-link type="primary" href="/home" icon="DArrowLeft" class="back-link"
          >返回门户首页</el-link
        >
      </div>
    </div>

    <!-- 右侧登录表单 -->
    <div class="login-form-section">
      <el-card class="login-card">
        <h3 style="text-align: left; margin-bottom: 65px">密码登录</h3>
        <el-form
          @keydown.enter="onSubmit"
          :model="loginForm"
          ref="formRef"
          :rules="rules"
          label-position="top"
        >
          <el-form-item prop="type" label="用户类型" v-if="type == 'mc'"
            ><el-select v-model="loginForm.userType" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="username" label="账号">
            <el-input v-model="loginForm.username" placeholder="请输入手机号码">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" label="验证码" v-if="captchaEnabled">
            <div class="register-tip">
              <el-input
                v-model="loginForm.code"
                auto-complete="off"
                placeholder="验证码"
                style="flex: 0.9"
              >
                <svg-icon
                  slot="prefix"
                  icon-class="validCode"
                  class="el-input__icon input-icon"
                />
              </el-input>

              <div class="register-code">
                <img
                  :src="codeUrl"
                  @click="getCode"
                  class="register-code-img"
                />
              </div>
            </div>
          </el-form-item>
          <el-button
            type="primary"
            block
            size="large"
            style="
              margin-top: 22px;
              width: 100%;
              border-radius: 10px;
              background: linear-gradient(
                135deg,
                rgb(28, 96, 255) 0%,
                rgb(31, 181, 249) 100%
              );
            "
            @click="onSubmit"
            >立即登录</el-button
          >
          <div class="form-links" v-if="type != 'mc'">
            <el-link class="more" @click="navto('/registered')" type="primary"
              >注册账号</el-link
            >
            <el-link class="more" @click="navto('/forget')" type="primary"
              >忘记密码?</el-link
            >
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import Header from "../../components/Header.vue";
import { showMessage } from "../../utils/common";
import { getCodeImg } from "@/api/login";
import { spLogin, vendorInfo, compereLogin, compereInfo } from "@/api/vendor";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const route = useRoute();
const type = computed(() => route.query.type);

const formRef = ref(null);
const captchaEnabled = ref(false);
const codeUrl = ref("");
const router = useRouter();
const loginForm = reactive({
  username: "",
  password: "",
  code: "",
  uuid: "",
  userType: "",
});
// 定义选项数据
const options = [
  { value: "", label: "请选择" },
  { value: "judge_compere", label: "评审主持人" },
  { value: "judge_jury", label: "评委" },
  { value: "judge_custodian", label: "评审监督人" },
];
const rules = ref({
  username: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (route.query.type == "mc" && loginForm.userType == "") {
        ElMessage({ message: "请选择用户类型", type: "error" });
        return;
      }
      const loginFunction = loginForm.userType ? compereLogin : spLogin;
      loginFunction(loginForm)
        .then((res) => {
          if (res.code == 200) {
            showMessage(res.msg, "success");
            localStorage.setItem("token", "Bearer " + res.data);
            getSupplierInfo();
          }
        })
        .catch((err) => {
          // 打印错误，查看结构
          // console.log("错误信息:", err);

          // 提取错误信息
          let errorMessage = "";
          if (typeof err === "string") {
            errorMessage = err;
          } else if (
            err.response &&
            err.response.data &&
            err.response.data.message
          ) {
            errorMessage = err.response.data.message;
          } else if (err.message) {
            errorMessage = err.message;
          }

          // 错误判断
          if (
            errorMessage.includes("验证码错误") ||
            errorMessage.includes("验证码已失效")
          ) {
            getCode(); // 重新获取验证码
          } else {
            console.error("其他错误:", errorMessage);
          }
        });
    } else {
      ElMessage({ message: "表单出错", type: "error" });
    }
  });
};
//获取供应商详细信息
const getSupplierInfo = async () => {
  if (type.value == "mc") {
    await compereInfo().then((res) => {
      if (res.code == 200) {
        localStorage.setItem("judgeInfo", JSON.stringify(res.data));
        router.push("/index");
      }
    });
  } else {
    await vendorInfo().then((res) => {
      if (res.code == 200) {
        localStorage.setItem("supplierInfo", JSON.stringify(res.data));
        router.push("/index");
      }
    });
  }
};
const navto = (url) => {
  router.push(url);
};
const getCode = () => {
  getCodeImg().then((res) => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.uuid = res.uuid;
    }
  });
};
const signOut = () => {
  localStorage.clear();
};
onMounted(() => {
  signOut()
  getCode();
});
</script>

<style lang="scss" scoped>
.login-page {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 56px);
  background: url("../../assets/back-login.png") no-repeat center center;
  background-size: cover;

  .welcome-section {
    display: flex;
    width: 686px;
    height: 476px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4);
    backdrop-filter: blur(5px);
    .welcome-text {
      padding: 50px 30px 20px 30px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: space-between;

      h1 {
        font-size: 36px;
        margin-bottom: 5px;
        color: #347ff7;
      }

      p {
        font-size: 20px;
        margin-bottom: 20px;
      }

      .back-link {
        font-size: 14px;
      }
    }
  }

  .login-form-section {
    display: flex;
    justify-content: center;
    align-items: center;
    .login-card {
      width: 400px;
      padding: 20px;
      padding-bottom: 97px;
      h3 {
        text-align: center;
        font-size: 24px;
        margin-bottom: 20px;
      }

      .captcha-container {
        display: flex;
        align-items: center;
        gap: 10px;

        .captcha-image {
          width: 100px;
          height: 40px;
          object-fit: cover;
          border-radius: 4px;
        }
      }

      .form-links {
        display: flex;
        justify-content: space-between;
        margin-top: 30px;

        a {
          font-size: 14px;
        }
      }
    }
  }
}
::v-deep .el-form-item {
  margin-bottom: 25px;
}
.register-tip {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .register-code {
    height: 32px;
    img {
      height: 32px;
    }
  }
}
</style>
